package ltd.dujiabao.orderservice.service;

import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import ltd.dujiabao.common.dto.DeductStockDto;
import ltd.dujiabao.orderservice.dao.OrderRepository;
import ltd.dujiabao.orderservice.domain.dto.CreateOrderDto;
import ltd.dujiabao.orderservice.domain.entity.Order;
import ltd.dujiabao.orderservice.rpc.InventoryApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author Bowie Du
 * @date 2025/7/22 20:01
 */
@Slf4j
@Service
public class OrderService {
    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private InventoryApi inventoryApi;

    @GlobalTransactional(rollbackFor = Exception.class)
    public void createOrder(CreateOrderDto dto) {
        log.info("XID: {}", RootContext.getXID());
        LocalDateTime now = LocalDateTime.now();
        Order order = new Order()
                .setUserId(dto.getUserId())
                .setProductId(dto.getProductId())
                .setQuantity(dto.getQuantity())
                .setCreatedAt(now)
                .setUpdatedAt(now);
        order = orderRepository.save(order);

        DeductStockDto deductStockDto = new DeductStockDto()
                .setProductId(dto.getProductId())
                .setQuantity(dto.getQuantity());
        inventoryApi.deductStock(deductStockDto);

        throw new RuntimeException("");
    }
}
